package com.kaifamiao.jsp.servlet;

import com.kaifamiao.jsp.entity.Customer;
import com.kaifamiao.utils.JdbcHelper;
import com.kaifamiao.utils.RowHandler;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;
import java.util.logging.Logger;

@WebServlet( "/customer/list" )
public class CustomerListServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void doGet(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        JdbcHelper helper = JdbcHelper.getInstance();
        // 查询 t_customers 表中所有的数据
        String sql = "SELECT id , username , password , nickname , name , gender , birthdate " +
                     "FROM t_customers ORDER BY id";
        RowHandler<Customer> handler = new RowHandler<Customer>() {
            @Override
            public Customer handle(ResultSet rs) throws SQLException {
                Customer c = new Customer();
                c.setId( rs.getInt( "id" ) );
                c.setUsername( rs.getString( "username" ) );
                c.setPassword( rs.getString( "password" ) );
                c.setNickname( rs.getString( "nickname" ) );
                c.setName( rs.getString( "name" ) );
                c.setGender( rs.getString( "gender" ) );
                java.sql.Date date = rs.getDate( "birthdate" );
                LocalDate birthdate = date.toLocalDate();
                c.setBirthdate( birthdate );
                return c;
            }
        };
        List<Customer> list = helper.query( sql , handler);
        helper.release();

        // 将数据保存到 request 的属性中
        request.setAttribute( "customers" , list );

        // 转发到 /WEB-INF/list.jsp
        RequestDispatcher dispatcher = request.getRequestDispatcher( "/WEB-INF/list.jsp" );
        dispatcher.forward( request , response );
    }
}
